<template>
  <div class="withdrawal-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>账户总览</span>
        </div>
      </template>
      <div class="account-overview">
        <div class="account-item">
          <div class="account-label">账户余额</div>
          <div class="account-value">{{ totalBalance }}</div>
          <div class="account-unit">元</div>
        </div>
        <div class="account-item">
          <div class="account-label">可提现金额</div>
          <div class="account-value highlight">{{ withdrawableAmount }}</div>
          <div class="account-unit">元</div>
        </div>
        <div class="withdrawal-tips">
          <i class="el-icon-info"></i>
          <span>每月25号后可提现上月收益，未提现金额将累计到下月</span>
        </div>
      </div>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>申请提现</span>
        </div>
      </template>
      <el-form ref="withdrawalForm" :model="withdrawalForm" :rules="withdrawalRules" label-width="80px">
        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawalForm.amount"
            :min="0.01"
            :max="withdrawableAmount"
            :precision="2"
            placeholder="请输入提现金额"
            style="width: 200px;">
          </el-input-number>
          <span class="available-amount">可用余额：{{ withdrawableAmount }}元</span>
        </el-form-item>
        <el-form-item label="提现账户" prop="account">
          <el-input v-model="withdrawalForm.account" placeholder="请输入支付宝账户"></el-input>
        </el-form-item>
        <el-form-item label="账户姓名" prop="accountName">
          <el-input v-model="withdrawalForm.accountName" placeholder="请输入账户姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitWithdrawal" :loading="submitting">提交提现申请</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>提现记录</span>
        </div>
      </template>
      <div class="withdrawal-records">
        <el-table v-loading="loading" :data="withdrawalRecords" style="width: 100%">
          <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
          <el-table-column prop="amount" label="提现金额" width="120">
            <template slot-scope="scope">{{ scope.row.amount }}元</template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 0" type="info">待处理</el-tag>
              <el-tag v-else-if="scope.row.status === 1" type="success">已完成</el-tag>
              <el-tag v-else-if="scope.row.status === 2" type="danger">已拒绝</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="申请时间" width="180"></el-table-column>
          <el-table-column prop="processTime" label="处理时间" width="180"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column label="操作" width="80" v-if="showActionColumn">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status === 0" type="text" @click="cancelWithdrawal(scope.row.id)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container" v-if="total > 0">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getAccountInfo, submitWithdrawal, getWithdrawalRecords, cancelWithdrawal } from '@/api/admin/withdrawal';

export default {
  name: 'Withdrawal',
  data() {
    return {
      // 账户信息
      totalBalance: '0.00',
      withdrawableAmount: '0.00',
      // 提现表单
      withdrawalForm: {
        amount: '',
        account: '',
        accountName: ''
      },
      withdrawalRules: {
        amount: [
          { required: true, message: '请输入提现金额', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '提现金额必须大于0.01元', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入支付宝账户', trigger: 'blur' }
        ],
        accountName: [
          { required: true, message: '请输入账户姓名', trigger: 'blur' }
        ]
      },
      // 提现记录
      withdrawalRecords: [],
      total: 0,
      loading: false,
      submitting: false,
      showActionColumn: true,
      pagination: {
        currentPage: 1,
        pageSize: 10
      }
    };
  },
  mounted() {
    this.loadAccountInfo();
    this.loadWithdrawalRecords();
  },
  methods: {
    // 加载账户信息
    loadAccountInfo() {
      getAccountInfo().then(response => {
        this.totalBalance = response.totalBalance || '0.00';
        this.withdrawableAmount = response.withdrawableAmount || '0.00';
      }).catch(error => {
        this.$message.error('获取账户信息失败');
        console.error('获取账户信息失败:', error);
      });
    },

    // 提交提现申请
    submitWithdrawal() {
      this.$refs.withdrawalForm.validate((valid) => {
        if (valid) {
          // 验证提现金额不超过可提现金额
          const amount = parseFloat(this.withdrawalForm.amount);
          const available = parseFloat(this.withdrawableAmount);

          if (amount > available) {
            this.$message.error('提现金额不能超过可提现金额');
            return;
          }

          this.submitting = true;
          submitWithdrawal(this.withdrawalForm).then(response => {
            this.$message.success('提现申请提交成功');
            this.resetForm();
            // 刷新账户信息和提现记录
            this.loadAccountInfo();
            this.loadWithdrawalRecords();
          }).catch(error => {
            this.$message.error('提现申请提交失败');
            console.error('提现申请提交失败:', error);
          }).finally(() => {
            this.submitting = false;
          });
        }
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.withdrawalForm.resetFields();
    },

    // 加载提现记录
    loadWithdrawalRecords() {
      this.loading = true;
      const params = {
        pageNum: this.pagination.currentPage,
        pageSize: this.pagination.pageSize
      };

      getWithdrawalRecords(params).then(response => {
        this.withdrawalRecords = response.rows || [];
        this.total = response.total || 0;
      }).catch(error => {
        this.$message.error('获取提现记录失败');
        console.error('获取提现记录失败:', error);
      }).finally(() => {
        this.loading = false;
      });
    },

    // 取消提现申请
    cancelWithdrawal(recordId) {
      this.$confirm('确定要取消该提现申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelWithdrawal(recordId).then(response => {
          this.$message.success('提现申请已取消');
          this.loadWithdrawalRecords();
          this.loadAccountInfo();
        }).catch(error => {
          this.$message.error('取消提现申请失败');
          console.error('取消提现申请失败:', error);
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },

    // 分页处理
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.loadWithdrawalRecords();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.loadWithdrawalRecords();
    }
  }
};
</script>

<style scoped>
.withdrawal-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.account-overview {
  display: flex;
  flex-wrap: wrap;
  gap: 40px;
}

.account-item {
  display: flex;
  align-items: baseline;
}

.account-label {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.account-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.account-value.highlight {
  color: #e6a23c;
}

.account-unit {
  font-size: 14px;
  color: #606266;
  margin-left: 5px;
}

.withdrawal-tips {
  margin-top: 20px;
  padding: 10px 15px;
  background-color: #f4f4f5;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  width: 100%;
}

.available-amount {
  margin-left: 20px;
  color: #909399;
  font-size: 12px;
}

.withdrawal-records {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
